package com.kiell.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.kiell.common.exception.NoStockException;
import com.kiell.common.to.OrderTo;
import com.kiell.common.to.mq.StockDetailTo;
import com.kiell.common.to.mq.StockLockedTo;
import com.kiell.common.utils.R;
import com.kiell.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.kiell.gulimall.ware.entity.WareOrderTaskEntity;
import com.kiell.gulimall.ware.feign.OrderFeignService;
import com.kiell.gulimall.ware.feign.ProductFeignService;
import com.kiell.gulimall.ware.service.WareOrderTaskDetailService;
import com.kiell.gulimall.ware.service.WareOrderTaskService;
import com.kiell.gulimall.ware.vo.OrderItemVo;
import com.kiell.gulimall.ware.vo.OrderVo;
import com.kiell.gulimall.ware.vo.SkuHasStockVo;
import com.kiell.gulimall.ware.vo.WareSkuLockVo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kiell.common.utils.PageUtils;
import com.kiell.common.utils.Query;

import com.kiell.gulimall.ware.dao.WareSkuDao;
import com.kiell.gulimall.ware.entity.WareSkuEntity;
import com.kiell.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private WareSkuDao wareSkuDao;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WareOrderTaskService orderTaskService;

    @Autowired
    private WareOrderTaskDetailService orderTaskDetailService;

    @Autowired
    private OrderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /**
         *    wareId: 123,//仓库id
         *    skuId: 123//商品id
         */
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)){
            queryWrapper.eq("sku_id",skuId);
        }
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)){
            queryWrapper.eq("ware_id",wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /** 添加库存
     * @param skuId
     * @param wareId
     * @param skuNum
     */
    @Transactional
    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //没有库存记录就新增
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>()
                                                                            .eq("sku_id", skuId)
                                                                            .eq("ware_id", wareId));
        if (wareSkuEntities.isEmpty()){
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            //TODO 远程查询sku的名字，如果失败，整个事务无需回滚
            //1、自己catch异常
            //TODO 还可以用什么办法让异常出现以后不回滚？高级
            try {
                R info = productFeignService.info(skuId);
                Map<String,Object> data = (Map<String, Object>) info.get("skuInfo");

                if(info.getCode() == 0){
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            wareSkuDao.insert(wareSkuEntity);
        }else{
            wareSkuDao.addStock(skuId,wareId,skuNum);
        }

    }

    /**
     * @param skuIds
     * @return
     */
    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(sku -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            //查询当前sku库存量
            Long count = this.wareSkuDao.getSkuStock(sku);
            skuHasStockVo.setSkuId(sku);
            skuHasStockVo.setHasStock(count == null? false:count > 0);
            return skuHasStockVo;
        }).collect(Collectors.toList());

        return collect;
    }


    /**
     * 锁定指定订单的库存
     * @param wareSkuLockVo
     * @return
     * (rollbackFor = NoStockException.class)
     * 默认只要是运行时异常都会回滚
     * 已锁定库存解锁场景：
     *      1.下单成功，订单过期没支付被系统自动取消。被用户自动取消。都要解锁库存
     *      2.下订单成功，库存锁定成功。接下来的业务调用失败，导致订单回滚。之前锁定的库存要自动解锁。（seata回滚高并发的话太慢）
     */
    @Transactional
    @Override
    public Boolean orderLockStcok(WareSkuLockVo wareSkuLockVo) {
        //保存库存工作单详情，追溯
        WareOrderTaskEntity orderTaskEntity = new WareOrderTaskEntity();
        orderTaskEntity.setOrderSn(wareSkuLockVo.getOrderSn());
        orderTaskEntity.setCreateTime(new Date());
        orderTaskService.save(orderTaskEntity);

        //1、按照下单的地址，找到就近仓库、锁定库存
        //2、找到每个商品在哪个仓库有库存
        List<OrderItemVo> locks = wareSkuLockVo.getLocks();
        List<SkuHasStock> hasStocks = locks.stream().map(item -> {
            Long skuId = item.getSkuId();
            SkuHasStock skuHasStock = new SkuHasStock();
            skuHasStock.setSkuId(skuId);
            skuHasStock.setNum(item.getCount());
            //查询商品在哪些仓库有库存
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            skuHasStock.setWareIds(wareIds);
            return skuHasStock;
        }).collect(Collectors.toList());

        //锁定库存
        //1、如果每一个商品都锁定成功,将当前商品锁定了几件的工作单记录发给MQ
        //2、锁定失败。前面保存的工作单信息都回滚了。发送出去的消息，即使要解锁库存，由于在数据库查不到指定的id，所有就不用解锁
        for (SkuHasStock skuHasStock:hasStocks){
            Boolean skuStocked = false;
            Long skuId = skuHasStock.getSkuId();
            List<Long> wareIds = skuHasStock.getWareIds();
            if (wareIds.isEmpty()){
                throw new NoStockException(skuId);
            }
            for(Long wareId:wareIds){
                // 成功就返回1，否则就返回0
                Long count = wareSkuDao.lockSkuStock(skuId,wareId,skuHasStock.getNum());
                if (count == 1){
                    skuStocked = true;
                    //TODO 告诉MQ库存锁定成功
                    //保存工作单关联详情所订单
                    WareOrderTaskDetailEntity taskDetailEntity = WareOrderTaskDetailEntity.builder()
                                                              .skuId(skuId)
                                                              .skuName("")
                                                              .skuNum(skuHasStock.getNum())
                                                              .taskId(orderTaskEntity.getId())
                                                              .wareId(wareId)
                                                              .lockStatus(1)
                                                              .build();
                    orderTaskDetailService.save(taskDetailEntity);
                    //TODO 告诉MQ库存锁定成功
                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(orderTaskEntity.getId());
                    StockDetailTo detailTo = new StockDetailTo();
                    BeanUtils.copyProperties(taskDetailEntity, detailTo);
                    lockedTo.setDetailTo(detailTo);
                    //告诉MQ库存锁定成功，生产者-交换机-死信队列-交换机-普通队列-消费者
                    //消息内容为库存锁定单传输对象，里面包括库存单id和库存详情单对象
                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",lockedTo);
                    break;
                } else {
                    // 当前仓库锁失败，重试下一个仓库
                }
            }
            if (skuStocked == false){
                // 当前商品所有仓库都没有锁住，其他商品也不需要锁了，直接返回没有库存了
                throw new NoStockException(skuId);
            }
        }
        // 3、运行到这，全部都是锁定成功的
        return true;
    }

    /**
     * 1、库存自动解锁
     *      下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚。之前锁定的库存就要自动解锁
     * 2、订单失败
     *      锁库存失败，则库存回滚了，这种情况无需解锁
     *      如何判断库存是否锁定失败呢？查询数据库关于这个订单的锁库存消息即可
     *  ！！！ 自动ACK机制：只要解决库存的消息失败，一定要告诉服务器解锁是失败的。启动手动ACK机制
     * @param to
     *
     */
    @Override
    public void unlockStock(StockLockedTo to) {
        //库存工作单的id
        StockDetailTo detail = to.getDetailTo();
        Long detailId = detail.getId();

        /**
         * 解锁
         * 1、查询数据库关于这个订单锁定库存信息
         *   有：证明库存锁定成功了
         *      解锁：订单状况
         *          1、没有这个订单，必须解锁库存
         *          2、有这个订单，不一定解锁库存
         *              订单状态：已取消：解锁库存
         *                      已支付：不能解锁库存
         *
         *   没有：库存锁定失败了，库存回滚了。无需解锁。
         */
        WareOrderTaskDetailEntity taskDetailInfo = orderTaskDetailService.getById(detailId);
        //有：证明库存锁定成功了
        if (taskDetailInfo != null) {
            //查出wms_ware_order_task工作单的信息
            Long id = to.getId();
            WareOrderTaskEntity orderTaskInfo = orderTaskService.getById(id);
            //获取订单号查询订单状态
            String orderSn = orderTaskInfo.getOrderSn();
            //远程查询订单信息
            R orderData = orderFeignService.getOrderStatus(orderSn);
            if (orderData.getCode() == 0) {
                //订单数据返回成功
                OrderVo orderInfo = orderData.getData("data", new TypeReference<OrderVo>() {});

                //判断订单状态是否已取消或者支付或者订单不存在
                if (orderInfo == null || orderInfo.getStatus() == 4) {
                    //订单已被取消，才能解锁库存
                    if (taskDetailInfo.getLockStatus() == 1) {
                        //当前库存工作单详情状态1，已锁定，但是未解锁才可以解锁
                        unLockStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum(),detailId);
                    }
                }
            } else {
                //消息拒绝以后重新放在队列里面，让别人继续消费解锁
                //远程调用服务失败
                throw new RuntimeException("远程调用服务失败");
            }
        } else {
            //无需解锁
        }
    }

    /**
     * 防止订单服务卡顿，导致订单状态消息一直改不了，库存优先到期，查订单状态新建，什么都不处理
     * 导致卡顿的订单，永远都不能解锁库存
     * @param orderTo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        // 查一下最新库存的状态，防止重复解锁库存
        WareOrderTaskEntity task = orderTaskService.getOrderTaskByOrderSn(orderSn);
        Long taskId = task.getId();
        // 按照工作单找到所有 没有解锁的库存，进行解锁
        List<WareOrderTaskDetailEntity> entities = orderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                                                                                       .eq("task_id", taskId)
                                                                                       .eq("lock_status", 1));
        // 进行解锁
        for (WareOrderTaskDetailEntity entity : entities) {
            unLockStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum(),entity.getId());
        }
        log.info("******解锁订单成功！id：{}******",orderTo.getId());
    }

    /**
     * 扣减库存
     * @param orderSn
     * @return
     */
    @Override
    public boolean deductionStock(String orderSn) {
        WareOrderTaskEntity task = orderTaskService.getOrderTaskByOrderSn(orderSn);
        Long taskId = task.getId();
        // 按照工作单找到所有 没有解锁的库存，进行解锁
        List<WareOrderTaskDetailEntity> entities = orderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                                                                                       .eq("task_id", taskId)
                                                                                       .eq("lock_status", 1));
        // 进行扣减
        for (WareOrderTaskDetailEntity entity : entities) {
            int deductionStock = this.baseMapper.deductionStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum());
            if (deductionStock >0){
                orderTaskDetailService.beDeduction(entity.getId());
            }
        }
        return true;
    }

    /**
     * 解锁库存的方法
     * @param skuId
     * @param wareId
     * @param num
     * @param taskDetailId
     */
    public void unLockStock(Long skuId,Long wareId,Integer num,Long taskDetailId) {

        //库存解锁
        wareSkuDao.unLockStock(skuId,wareId,num);

        //更新工作单的状态
        WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity();
        taskDetailEntity.setId(taskDetailId);
        //变为已解锁
        taskDetailEntity.setLockStatus(2);
        orderTaskDetailService.updateById(taskDetailEntity);
        log.info("订单库存自动解锁成功->>sku:{},num:{}",skuId,num);
    }


    /**
     * 内部类：哪些仓库有对应skuId商品的库存
     */
    @Data
    class SkuHasStock{
        private Long skuId;
        private Integer num;
        private List<Long> wareIds;
    }
}







